<?php

namespace App\Http\Controllers\Admin;

use App\Models\ViolateConfig;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
 * 违规设置
 */
class ViolateConfigController extends CommonController
{

    public $model = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new ViolateConfig();
    }

    /**
     * 详情
     */
    public function detail()
    {
        $violate_config = config("other.violate_config");
        if (empty($violate_config)) {
            return $this->returnApi(203, "暂无数据");
        }
        $now_data = $this->model->find(1);
        $data = [];
        foreach ($violate_config as $key => $val) {
            $data[$key]['number'] =  isset($now_data[$val['field']]) ? $now_data[$val['field']] : 0; //用户可违规次数   0 表示无违规规定 
            $data[$key]['clear_day'] =  isset($now_data[$val['field'] . '_clear_day']) ? $now_data[$val['field'] . '_clear_day'] : 0; //用户自动清空违规天数
            $data[$key]['name'] =   $val['name']; //名称
            $data[$key]['field'] =   $val['field']; //字段名
        }
        return $this->returnApi(200, "获取成功", true, $data);
    }

    /**
     * 修改违规设置 
     * @param id int 1  固定 1 
     * @param 根据列表返回字段名传参 xxx int 最大可违规次数   0 表示无限    （与xxx_clear_day必须同时对应 ）
     * @param xxx_clear_day int 预约自动清空天数 0 表示无限 (0表示永不清空)  若最大违规次数为0，则此参数无效
     */
    public function change()
    {
        $violate_config = config("other.violate_config");

        $res = $this->model->where('id', 1)->first();
        if (empty($res)) {
            $res = $this->model;
        }
        $data = $this->request->all();
        foreach ($violate_config as $key => $val) {
            if (!isset($data[$val['field']])) {
              //  return $this->returnApi(201, "请检查填写的数据");
                continue;
            }
            if (!is_numeric($data[$val['field']]) || !is_numeric($data[$val['field'] . '_clear_day'])) {
                return $this->returnApi(201, "请检查填写的数据,只能为纯数字");
            }

            $res->{$val['field']} = $data[$val['field']];
            $res->{$val['field'] . '_clear_day'} = $data[$val['field'] . '_clear_day'];
        }
        $result = $res->save();

        if (!$result) {
            return $this->returnApi(201, "设置失败");
        }

        Cache::forget('violate_number');//重置违规数量
        return $this->returnApi(200, "设置成功", true);
    }
}
